use core::ops::Deref;

use pc_keyboard::{layouts, DecodedKey, HandleControl, Keyboard, ScancodeSet1};
use spin::Mutex;
use x86_64::instructions::port::Port;
use crate::driver::keyboard;
use crate::init::pic::PICS;
use crate::init::idt::InterruptIndex;
use crate::print;

lazy_static::lazy_static! {
    pub static ref KEYBOARD_BUFFER: Mutex<[u8; 1000]> = Mutex::new([0; 1000]);
    pub static ref INDEX: Mutex<usize> = Mutex::new(0);
}



lazy_static::lazy_static! {
    pub static ref PORT: Mutex<Port<u8>> = Mutex::new(Port::new(0x60));
}

lazy_static::lazy_static! {
        static ref KEYBOARD: Mutex<Keyboard<layouts::Us104Key, ScancodeSet1>> =
            Mutex::new(Keyboard::new(ScancodeSet1::new(),
                layouts::Us104Key, HandleControl::Ignore)
            );
    }

pub fn handle_interrupt() {
    let mut keyboard = KEYBOARD.lock();
    let mut port = PORT.lock();

    let scancode: u8 = unsafe { port.read() };
    if let Ok(Some(key_event)) = keyboard.add_byte(scancode) {
        if let Some(key) = keyboard.process_keyevent(key_event) {
            match key {
                DecodedKey::Unicode(character) => {
                    print!("{}", character);
                    let mut buffer = KEYBOARD_BUFFER.lock();
                    let mut index = INDEX.lock();
                    buffer[*index] = character as u8;
                    *index += 1;
                }

                DecodedKey::RawKey(key) => {

                    match key {
                        pc_keyboard::KeyCode::Backspace => {
                            // 处理 Backspace 键
                            let mut buffer = KEYBOARD_BUFFER.lock();
                            let mut index = INDEX.lock();
                            if *index > 0 {
                                *index -= 1;
                                buffer[*index] = 0;  // 清除最后一个字符
                                // 调用 VGA 驱动的退格功能
                                crate::vga::WRITER.lock().backspace();
                            }
                        }
                        
                    }
                }
            }
        }
    }

    unsafe {
        PICS.lock()
            .notify_end_of_interrupt(InterruptIndex::Keyboard.as_u8());
    }
}
